import routes, { IRouteObject } from "@/router"
import { __DEV__ } from "@/types/global"
import { useState } from "react"
import { useLocation, useNavigate, useRoutes } from "react-router-dom"

export interface IRouter {
    name: string,
    params?: Object,
    query?: Object,
}

let routerMap: Map<string, string> = new Map<string, string>()
console.log('routerMap', routerMap)
export const useRouter = () => {
    const _routes = routes.map(item => item)
    const navigator = useNavigate()
    const location = useLocation()

    const setMap = (item: IRouteObject, _path: string) => {
        if(routerMap.has(item.name)) {
            if(__DEV__) {
                console.error(`${item} 中的 name 字段不能重复`)
                return
            }
        }

        routerMap.set(item.name, _path)
    }

    if(routerMap.size <= 0) {
        const getRoutesMap = (list: IRouteObject[], path: string): string => {
            list.forEach((item: IRouteObject) => {
                const _p: string = item.path ? item.path?.replace(/\//, '') : ''
                let _path: string = _p ? `${path}/${_p}` : path
                
                if(item.path === '/' && path === '') {
                    _path = '/'
                }
                
                
                if(__DEV__) {
                    if(!item.name && item.path !== '/') {
                        console.error(`${item} 中的 name 字段不能为空`)
                        return
                    }
                }
    
                if(item.children) {
                    setMap(item, _path)
                    getRoutesMap(item.children, _path)
                } else {
                    setMap(item, _path)
                }
            })
    
            return path
        }
        getRoutesMap(_routes, '')
    }
    
    console.log('routerMap', routerMap)
    const push = (data: IRouter, option?: any) => {
        const { name } = data
        if(!name) return
        const url: string = routerMap.get(name) ?? ''
        option ? navigator(url, option) : navigator(url)
    }

    const getKeyByValue = (value: string): string => {
        for(let item of routerMap) {
            if(item[1] === value) {
                return item[0]
            }
        }

        return ''
    }
    const getCurrentRouter = () => getKeyByValue(location.pathname)

    return {
        push,
        getCurrentRouter
    }
}